//
//  TJPublishVideoController.m
//  BaoDian
//
//  Created by mac on 2024/8/17.
//

#import "TJPublishVideoController.h"
#import "TJVideoCoverDownloader.h"
#import "TJStyle1Button.h"
#import "QMUITextView.h"
#import "TJVideoPlayController.h"
#import "TJUrlDataModel.h"
#import "TJPhotosTool.h"
#import "TJTaskModel.h"
#import <DouyinOpenSDK/DouyinOpenSDKShare.h>

@interface TJPublishVideoController ()

@property (nonatomic, weak) QMUITextView *textView;
@property (nonatomic, strong) UIImage *coverImage;
@property (nonatomic, weak) UIImageView *coverImageView;
@property (nonatomic, weak) UISwitch *switchView;

@end

@implementation TJPublishVideoController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    UIScrollView *scrollView = [UIScrollView addToView:self.view];
    scrollView.frame = CGRectMake(0, KNavBarHight, KScreenWidth, KScreenHeight - KNavBarHight - TabbarSafeBottomMargin - 20 - buttonHeight);
    CGSize contentSize = scrollView.bounds.size;
    scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    scrollView.contentSize = contentSize;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.alwaysBounceVertical = YES;
    scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    
    UIView *contentView = [[UIView alloc] init].addTo(scrollView);
    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
        make.width.offset(contentSize.width);
        make.height.offset(contentSize.height);
    }];
    
    UIImageView *coverImageView = [UIImageView addToView:contentView];
    coverImageView.addCornerRadius(12);
    coverImageView.userInteractionEnabled = YES;
    coverImageView.contentMode = UIViewContentModeScaleAspectFit;
    CGFloat width = KScreenWidth - 32;
    coverImageView.backgroundColor = UIColor.blackColor;
    [coverImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.offset(width);
        make.centerX.offset(0);
        make.top.offset(0);
        make.height.offset(352);
    }];
    
    UIImageView *playerIconView = [UIImageView addToView:coverImageView];
    [playerIconView addTapGesturesWithTarget:self action:@selector(tapPlayerView)];
    playerIconView.image = [UIImage imageNamed:@"videoPlayer_icon"];
    [playerIconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.offset(0);
    }];
    
    UILabel *textLabel = [UILabel lableWithSuperView:contentView font:UIFontSemiboldMake(16) color:UIColor.whiteColor title:self.detailData[@"videoName"] textAlignment:NSTextAlignmentLeft];
    textLabel.numberOfLines = 0;
    [textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(16);
        make.top.equalTo(coverImageView.mas_bottom).offset(10);
    }];
    
    UIView *tempView = nil;
    if (self.model.hasPoi.boolValue) {
        
        UIView *POIView = [UIView addToView:contentView];
        POIView.backgroundColor = UIColorMake(0x303137);
        POIView.addCornerRadius(8);
        [POIView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.inset(16);
            make.top.equalTo(textLabel.mas_bottom).offset(16);
            make.height.offset(40);
        }];
        
        UILabel *poiLabel = [UILabel lableWithSuperView:POIView font:UIFontMake(14) color:UIColor.whiteColor title:@"是否挂载POI" textAlignment:NSTextAlignmentCenter];
        [poiLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.inset(10);
            make.centerY.offset(0);
        }];
        
        UISwitch *switchView = [UISwitch addToView:POIView];
        switchView.onTintColor = UIColor.tj_mainColor;
        switchView.on = YES;
        switchView.transform = CGAffineTransformMakeScale(0.8, 0.8);
        [switchView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.inset(12);
            make.centerY.offset(0);
        }];
        _switchView = switchView;
        tempView = POIView;
    } else {
        tempView = textLabel;
    }
    
    UILabel *publishLabel = [UILabel lableWithSuperView:contentView font:UIFontMake(14) color:UIColor.tj_8D9298Color title:@"发布文案" textAlignment:NSTextAlignmentCenter];
    [publishLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.inset(16);
        if ([tempView isKindOfClass:UILabel.class]) {
            make.top.equalTo(tempView.mas_bottom).offset(16);
        } else {
            make.top.equalTo(tempView.mas_bottom).offset(18);
        }
    }];

    UIView *textContentView = [UIView addToView:contentView];
    textContentView.backgroundColor = UIColorMake(0x303137);
    textContentView.addCornerRadius(8);
    [textContentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(16);
        make.top.equalTo(publishLabel.mas_bottom).offset(8);
        make.height.offset(100);
    }];
    
    QMUITextView *textView = [QMUITextView addToView:textContentView];
    textView.placeholder = @"请输入发布文案";
    textView.text = self.detailData[@"text"];
    textView.font = UIFontMake(14);
    textView.maximumTextLength = 200;
    textView.textColor = UIColor.whiteColor;
    textView.backgroundColor = UIColorMake(0x303137);
    textView.placeholderColor = UIColor.tj_placeholderTextColor;
    [textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(4);
        make.top.bottom.inset(4);
    }];
    
    TJStyle1Button *publishButton = [TJStyle1Button buttonWithSuperView:self.view font:UIFontMediumMake(16) color:nil title:@"去发布"];
    [publishButton addTarget:self action:@selector(didClickPublishButton) forControlEvents:UIControlEventTouchUpInside];
    [publishButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.inset(16);
        make.height.offset(buttonHeight);
        make.bottom.inset(TabbarSafeBottomMargin + 10);
    }];
    
    [self.view setNeedsLayout];
    [self.view layoutIfNeeded];
    
    scrollView.contentSize = CGSizeMake(scrollView.contentSize.width, textContentView.tj_MaxY + 10);
    [contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.offset(contentSize.height);
    }];
    
    _textView = textView;
    _coverImageView = coverImageView;
    
    [[TJVideoCoverDownloader shareDownLoader] downloadWithUrl:self.data[@"videoUrl"] completion:^(UIImage * _Nullable thumbnail) {
        self.coverImage = thumbnail;
        self.coverImageView.image = thumbnail;
    }];
    
}
 
- (void)didClickPublishButton {
    
    [TJHUD showLoadingInView:self.view];
    [TJTemplatePresent createShareId:self.textView.text hasPoi:self.switchView.isOn videoEditId:self.data[@"id"] complete:^(NSDictionary * _Nonnull data, NSError * _Nullable error) {
        
        if (error) {
            return;
        }
        
        [TJTools copyStringToPasteboard:self.textView.text];
        
        TJTaskModel *taskModel = [[TJTaskModel alloc] init];
        taskModel.videoUrl = self.data[@"videoUrl"];
        taskModel.videoId = self.data[@"videoId"];
        taskModel.text = self.detailData[@"text"];
        taskModel.shareId = data[@"shareId"];
        taskModel.poiId = data[@"poiId"];
        taskModel.Id = data[@"id"];
        
        //一个url对应一个 localIdentifier, 如果没查到就下载
        TJUrlDataModel *dataModel = [TJUrlDataModel modelWithUrl:self.data[@"videoId"]];
        if (dataModel && dataModel.localIdentifier) { //检查相册里面有没有, 没有就下载
            [TJPhotosTool fetchVideoWithLocalIdentifier:dataModel.localIdentifier completion:^(AVAsset * _Nonnull videoAsset) {
                if (videoAsset) {
                    [self sendToDouYin:dataModel.localIdentifier taskModel:taskModel];
                } else {
                    [self downloadWithModel:taskModel];
                }
            }];
        } else {//下载
            [self downloadWithModel:taskModel];
        }
        
    }];
}

- (void)downloadWithModel:(TJTaskModel *)model {
    
    TJUrlDataModel *dataModel = [[TJUrlDataModel alloc] init];
    dataModel.url = model.videoUrl;
    
    NSString *localPath = [NSString stringWithFormat:@"%@.%@",  model.videoUrl.md5,  model.videoUrl.pathExtension].tj_cachePath;
    if ([[NSFileManager defaultManager] fileExistsAtPath:localPath]) {
        [TJPhotosTool saveVideoToPhotoLibrary:[NSURL fileURLWithPath:localPath] completion:^(NSError * _Nonnull error, NSString * _Nonnull localIdentifier) {
            if (error) {
                return;
            }
            dataModel.localPath = localPath;
            dataModel.localIdentifier = localIdentifier;
            [dataModel bg_saveOrUpdate];
            [self sendToDouYin:localIdentifier taskModel:model];
        }];
    } else {
        [TJHUD showLoadingInView:self.view text:@"下载中"];
        TJDownloadFileWithUrl(model.videoUrl, ^(CGFloat value) {
            [TJHUD updateHudText:[NSString stringWithFormat:@"下载中%.2f%%", value * 100]];
        }, ^NSURL * _Nonnull{
            return [NSURL fileURLWithPath:localPath];
        }, ^(NSError * _Nullable error) {
            if (error) {
                [TJHUD showSucceedMessage:@"下载视频失败"];
                return;
            }
            
            [TJHUD hiddenLoading];
            
            dataModel.localPath = localPath;
            [dataModel bg_saveOrUpdate];
            
            [TJPhotosTool saveVideoToPhotoLibrary:[NSURL fileURLWithPath:localPath] completion:^(NSError * _Nonnull error, NSString * _Nonnull localIdentifier) {
                if (error) {
                    return;
                }
                dataModel.localIdentifier = localIdentifier;
                [dataModel bg_saveOrUpdate];
                [self sendToDouYin:localIdentifier taskModel:model];
            }];
        });
    }
}

- (void)sendToDouYin:(NSString *)localIdentifier taskModel:(TJTaskModel *)taskModel {
    
    dispatch_async_main_queue(^{
        
        DouyinOpenSDKShareRequest *req = [[DouyinOpenSDKShareRequest alloc] init];
        req.mediaType = DouyinOpenSDKShareMediaTypeVideo; // 分享的资源为纯视频类型
        req.localIdentifiers = @[localIdentifier]; // NSArray<NSString *> * （系统相册的本地标识符）
        req.landedPageType = DouyinOpenSDKLandedPagePublish; // 发布页面（需要抖音14.7版本以上）
        req.publishStory = NO; // 是否转发到日常,设置为YES的时使用转发到日常能力，设置为NO时使用投稿能力
        req.title = [DouyinOpenSDKShareTitle new];
        req.title.text = taskModel.text; // 正文
        req.state = taskModel.shareId;
        
        NSLog(@"req.localIdentifiers = %@", req.localIdentifiers);
        NSLog(@"req.state = %@", req.state);
        NSLog(@"req.title.text = %@", req.title.text);
        
        
        if (self.switchView.isOn) {
            req.poiID = taskModel.poiId;
        }
 
        [req sendShareRequestWithCompleteBlock:^(DouyinOpenSDKShareResponse * _Nonnull respond) {
            NSLog(@"respond.errCode = %ld", respond.errCode);
            NSLog(@"respond.errString = %@", respond.errString);
            NSLog(@"respond.state = %@", respond.state);
            NSLog(@"respond.state = %ld", respond.shareState);
            
            [TJTemplatePresent updateClockPlanWithId:taskModel.Id status:toString(@(respond.errCode)) complete:^(NSError * _Nullable error) {
                if (error) {
                    return;
                }
                [TJHUD showMessage:@"发布成功"];
                [self.navigationController popToRootViewControllerAnimated:YES];
            }];
        }];
        
    });
  
}


- (void)tapPlayerView {
    TJVideoPlayController *videoPlayController = [[TJVideoPlayController alloc] init];
    videoPlayController.url = self.data[@"videoUrl"];
    videoPlayController.coverImage = self.coverImage;
    [self presentViewController:videoPlayController animated:YES completion:nil];
}
 

@end
